﻿using Devonline.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Devonline.Database.TimeSeries.InfluxDB;

public static class ServiceExtensions
{
    /// <summary>
    /// 注册数据库上下文
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <param name="endpoint">InfluxDB 数据库配置项</param>
    /// <returns></returns>
    public static IServiceCollection AddInfluxDB(this IServiceCollection services, IDatabaseEndpoint? endpoint)
    {
        if (endpoint is not null)
        {
            services.AddKeyedScoped<ITimeSeriesDataService, InfluxDataService>(endpoint.Name, (serviceProvider, _) =>
            {
                var logger = serviceProvider.GetRequiredService<ILogger<InfluxDataService>>();
                var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
                return new InfluxDataService(logger, endpoint, httpContextAccessor);
            });
        }

        return services;
    }

    /// <summary>
    /// 注册数据库上下文
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <param name="endpoint">InfluxDB 数据库配置项</param>
    /// <returns></returns>
    public static IServiceCollection AddSingleInfluxDB(this IServiceCollection services, IDatabaseEndpoint? endpoint)
    {
        if (endpoint is not null)
        {
            services.AddSingleton(endpoint);
            services.AddSingleton<ITimeSeriesDataService, InfluxDataService>();
        }

        return services;
    }
}